package com.imflea.zero.service.task.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imflea.zero.utils.ZeroApplicationContextUtil;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.dto.IdDto;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.dao.task.ScheduleTaskMapper;
import com.imflea.zero.model.entity.task.ScheduleTask;
import com.imflea.zero.model.entity.task.dto.ScheduleTaskDto;
import com.imflea.zero.service.task.IScheduleTaskService;
import com.imflea.zero.service.task.IScheduledTaskJobService;
import com.imflea.zero.service.task.IScheduledTaskRunnerService;
import com.imflea.zero.utils.SessionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 定时任务配置表 服务实现类
 * </p>
 *
 * @author zhaoyang
 * @since 2022-01-14
 */
@Service
public class ScheduleTaskServiceImpl extends ServiceImpl<ScheduleTaskMapper, ScheduleTask> implements IScheduleTaskService {
    @Autowired
    private IScheduledTaskRunnerService scheduledTaskRunnerService;

    @Override
    public ScheduleTask saveOrUpdateScheduleTask(ScheduleTask entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
        }
        entity.setTenantId(SessionUtils.getTenantId());
        Boolean isOk = this.saveOrUpdate(entity);
        if (!isOk) {
            throw new BizException("定时任务更新失败");
        }
        return entity;
    }

    @Override
    public PageInfo<ScheduleTask> queryPage(ScheduleTaskDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        QueryWrapper<ScheduleTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        PageHelper.startPage(pageIndex, pageSize);
        List<ScheduleTask> adoptInfos = this.list(queryWrapper);
        PageInfo<ScheduleTask> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public Boolean updateJobStatus(IdDto taskId, String status) {

        ScheduleTask task = this.getById(taskId);

        try {
           ZeroApplicationContextUtil.getBean(task.getTaskKey(), IScheduledTaskJobService.class);
        } catch (Exception e) {
            throw new BizException("定时任务启动失败，未找到对应的bean");
        }

        Boolean isRunning = ("1").equals(task.getStatus());
        task.setStatus(status);
        this.updateById(task);
        if (status.equals("1") && !isRunning) {
            scheduledTaskRunnerService.start(task.getTaskKey(), task);
        } else {
            scheduledTaskRunnerService.stop(task.getTaskKey());
        }
        return true;
    }

}
